﻿using UnityEngine;
using System.Collections;

namespace Turret
{
    public class TurretSAMBehaviour : Turret
    {
        //public GameObject muzzeEffect;
        public Transform[] muzzlePosition;
        public Transform turretBall;
        public Transform pivot_tilt;
        public Transform pivot_pan;
        public Transform aim_tilt;
        public Transform aim_pan;

        protected override void Awake()
        {
            base.Awake();
        }

        // Use this for initialization
		protected override void Start()
        {
            base.Start();
            //Tags our turret will focus
            targetableTag[0] = "Ennemy_air";
        }

        protected override void getMyStatTemplates()
        {
            statTemplates = statManager.SAMTurretStat;
        }

        // Update is called once per frame
        protected override void Update()
        {
            base.Update();
            //If the target is set
            if (target)
            {
                //Rotate our pan and tilt empty object to guide the real objects (pivot_pan and pivot_tilt)
                aim_pan.LookAt(target);
                aim_pan.eulerAngles = new Vector3(0, aim_pan.eulerAngles.y, 0);
                aim_tilt.LookAt(target);

                //Lerp the pivots according to aim rotation to face our target
                pivot_pan.rotation = Quaternion.Lerp(pivot_pan.rotation, aim_pan.rotation, Time.deltaTime * turnSpeed);
                pivot_tilt.rotation = Quaternion.Lerp(pivot_tilt.rotation, aim_tilt.rotation, Time.deltaTime * turnSpeed);
            }

            //If it's time to fire
            if (Time.time >= nextFireTime)
            {
                fire();
            }
        }

        protected override void fire()
        {
            //Update the fire timer
            nextFireTime = Time.time + reloadTime;
            //Chose a random barrel
            int m = Random.Range(0, muzzlePosition.Length);
            //Create a new Missile and set it's target
            GameObject newMissile = (GameObject)Instantiate(projectile, muzzlePosition[m].position, muzzlePosition[m].rotation);
            newMissile.GetComponent<MissileBehaviour>().setTarget(target);
            newMissile.GetComponent<MissileBehaviour>().setStats(projectileRange, projectileSpeed, projectileDamage);
        }
    }
}
